<script setup lang='ts'>
import { ref, reactive, PropType, onBeforeMount } from 'vue'
import { ElMessage } from 'element-plus'
import { saveItemGroupItems, getItemGroupItemsOptional, getItemGroupItems, ItemGroupFormInfor, ItemData} from '@/api/physicalExaminationManager/projectPortfolio'
import { ColorTheme, ColorRed } from '@/api/config'

import dDialog from '@/components/dDialog/dDialog.vue'
import operation from '@/components/dTable/components/operation.vue'
import {SearchButton} from '@/components/dTable/dHeader'

import {TransferController} from '@/util/transfer'
import {HeaderData, Operation as Oper, TransRowOperbuttons} from '@/components/dTable/dTable'
import dTablePromote from '@/components/dTable/dTablePromote.vue'


//是否显示
const props = defineProps({
  //显示
  showDialog:{
    type:Boolean,
    required:true
  },

  //数据
  itemGroupFormData:{
    type:Object as PropType<ItemGroupFormInfor>,
    required:true
  }
})

// const {store} = useStore.setup()

const emits = defineEmits(['close'])

//信息
const fromData:ItemGroupFormInfor = reactive(props.itemGroupFormData)

// 显示加载状态
const showSaveLoading = ref(false)

let transferController:TransferController<ItemData&TransRowOperbuttons, ItemData&TransRowOperbuttons>|null = null

//关闭
const onClose = () => {
  emits('close')
}

//取消按钮
const onCancel = () => {
  onClose()
}

// 确认按钮
const onConfirm = () => {
  // validateFlag.value = !validateFlag.value
  if (transferController && fromData.id) {
    const leftData = transferController.getLeftData()
    // if (leftData.length === 0) {
    //   ElMessage.warning('请添加体检项目')
    //   return
    // }
    const arr:Array<string> = []
    for (let i = 0, l = leftData.length; i < l; i++) {
      const item = leftData[i]
      arr.push(item.id)
    }
    saveItemGroupItems({ id:fromData.id, itemIds:arr}).then(() => {
      ElMessage.success('保存成功')
      onClose()
    }).catch((error) => {
      console.warn(error)
    })
  }
}

/**穿梭表格数据*/
//数据
const leftTableData = ref<Array<ItemData&TransRowOperbuttons>>([])
const rightTableData = ref<Array<ItemData&TransRowOperbuttons>>([])

const hasDataNum = ref(0)

//表格数据
const leftTableHeaderData = ref<Array<HeaderData>>([
  {prop:'itemCode', label:'体检项目编码', columnType:'text', align:'left', 'min-width':'153'},
  {prop:'itemName', label:'体检项目名称', columnType:'text', align:'left', 'min-width':'153'},
  {prop:'operl', label:'操作', columnType:'slot', 'width':'65', fixed:'right'}
])
const rightTableHeaderData = ref<Array<HeaderData>>([
  {prop:'itemCode', label:'体检项目编码', columnType:'text', align:'left', 'min-width':'153'},
  {prop:'itemName', label:'体检项目名称', columnType:'text', align:'left', 'min-width':'153'},
  {prop:'operr', label:'操作', columnType:'slot', 'width':'65', fixed:'right'}
])

//左边操作栏
const leftRowOperButtons:Array<Oper> = [
  {code:'removeItem', label:'移除', iconConfig:{icon:'common-removeItem', type:'custom', color:ColorRed, size:20}}
]
const rightRowOperButtons:Array<Oper> = [
  {code:'addItem', label:'添加', iconConfig:{icon:'common-addItem', type:'custom', color:ColorTheme, size:20}}
]

//左边搜索
const leftSearchButtons = ref<Array<SearchButton>>([
  {type:'inputsearch', value:'', width:280, placeholder:'搜索体检项目编码或名称'}
])
//右边搜索
const rightSearchButtons = ref<Array<SearchButton>>([
  {type:'inputsearch', value:'', width:280, placeholder:'搜索体检项目编码或名称'}
])

//更新显示的数据
const updateData = () => {
  if (transferController) {
    const leftData = transferController.getLeftData()
    hasDataNum.value = leftData.length

    leftTableData.value = transferController.getShowLeftData()
    rightTableData.value = transferController.getShowRightData()

  }
}

//左边提交
const onLeftSubmit = () => {
  const item = leftSearchButtons.value[0]
  let keyword = ''
  if (item && item.type === 'inputsearch') {
    keyword = item.value ? item.value : ''
  }
  if (transferController) {
    transferController.changeLeftKey(keyword)
    updateData()
  }
}

//右边提交
const onRightSubmit = () => {
  const item = rightSearchButtons.value[0]
  let keyword = ''
  if (item && item.type === 'inputsearch') {
    keyword = item.value ? item.value : ''
  }
  if (transferController) {
    transferController.changeRightKey(keyword)
    updateData()
  }
}

//左边操作栏事件
const onLeftCellOperation = (code, row:ItemData & TransRowOperbuttons) => {
  if (code === 'removeItem' && transferController) {
    transferController.ltr([row])
    updateData()
  }
}
//右边操作栏事件
const onRightCellOperation = (code, row:ItemData & TransRowOperbuttons) => {
  if (code === 'addItem' && transferController) {
    transferController.rtl([row])
    updateData()
  }
}


//初始化可选和已选体检项目
const updateInitialItems = () => {
  getItemGroupItems(fromData.id).then(res => {
    const {data} = res.data
    if (data && transferController) {
      const leftData:Array<ItemData&TransRowOperbuttons> = []
      data.forEach((item) => {
        leftData.push({...item, operl:fromData.isFixed ? [] : leftRowOperButtons, operr:fromData.isFixed ? [] : rightRowOperButtons})
      })
      transferController.changeLeftData(leftData)
      updateData()
    }
  }).catch((res) => {
    console.warn(res)
    if (transferController) {
      transferController.changeLeftData([])
      transferController.changeRightData([])
      updateData()
    }
  })

  getItemGroupItemsOptional(fromData.id).then((res) => {
    const {data} = res.data
    if (data && transferController) {
      const rightData:Array<ItemData&TransRowOperbuttons> = []
      data.forEach((item) => {
        rightData.push({...item, operl:fromData.isFixed ? [] : leftRowOperButtons, operr:fromData.isFixed ? [] : rightRowOperButtons})
      })

      transferController.changeRightData(rightData)
      updateData()
    }
  }).catch((res) => {
    console.warn(res)
    if (transferController) {
      transferController.changeLeftData([])
      transferController.changeRightData([])
      updateData()
    }
  })
}

onBeforeMount(() => {
  updateInitialItems()
  transferController = new TransferController([], [], {'itemName':'itemName', 'itemCode':'itemCode', 'id':'id'}, {'itemName':'itemName', 'itemCode':'itemCode', 'id':'id'}, 'id', 'id', false, false, ['itemName', 'itemCode'], ['itemName', 'itemCode'])
})

</script>

<template>
  <d-dialog
    title="配置项目组合"
    width="1240px"
    :show-dialog="showDialog"
    :show-save-loading="showSaveLoading"
    @cancel="onCancel"
    @confirm="onConfirm"
    @close="onClose"
  >
    <div class="inspect-add-gap d-common-flex">
      <d-table-promote
        :label-width="100"
        :show-footer="false"
        :search-buttons="leftSearchButtons"
        :table-data="leftTableData"
        :table-header-data="leftTableHeaderData"
        @form-submit="onLeftSubmit"
      >
        <template #searchbutton-prepend>
          <div class="search-label">
            体检项目
          </div>
        </template>
        <template #operbutton-append>
          <div class="title">
            已选体检项目
          </div>
        </template>
        <template #operl="scope">
          <operation :row="scope.row" :col="scope.item" @opertion-click="onLeftCellOperation" />
        </template>
      </d-table-promote>
      <div class="d-common-space-1" />
      <d-table-promote
        :label-width="100"
        :show-footer="false"
        :search-buttons="rightSearchButtons"
        :table-data="rightTableData"
        :table-header-data="rightTableHeaderData"
        @form-submit="onRightSubmit"
      >
        <template #searchbutton-prepend>
          <div class="search-label">
            体检项目
          </div>
        </template>
        <template #operbutton-append>
          <div class="title">
            可选体检项目
          </div>
        </template>
        <template #operr="scope">
          <operation :row="scope.row" :col="scope.item" @opertion-click="onRightCellOperation" />
        </template>
      </d-table-promote>
    </div>
  </d-dialog>
</template>

<style scoped lang="less">
.inspect-add-gap{
  column-gap:var(--d-margin-level-3);
  width: 100%;
  height: 605px;
  :deep(.d-table-from-con){
    margin-bottom: 0;
  }
}
.search-label{
  line-height: 32px;
  margin-right:10px;
}
.title{
  font-weight: bold;
  margin-top: 18px;
}


</style>
